package com.kaka.starter.mybatis.plugin;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.kaka.starter.mybatis.dto.AuthParamDTO;
import org.apache.commons.lang3.StringUtils;

/**
 * @author kaka
 * @Date 2021/11/5
 */
public class AuthSqlFormat {


    public static String leftjoinFormat(AuthParamDTO authParamDTO) {

        //解析表结构使用 无实际用途
        String stringBuilder = "select * from tmp" +
                " left join (select DISTINCT table_id from kaka_table_auth where table_name = '${tableName}' ) auth" +
                " on ${mainTableAlias}.${id} = auth.table_id";
        return stringBuilder.replace("${id}", authParamDTO.getTableId())
                .replace("${mainTableAlias}", authParamDTO.getMainTableAlias())
                .replace("${tableName}", authParamDTO.getTableName());
    }

    public static String whereFormat(AuthParamDTO authParamDTO) {

        //模板sql
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(" (${mainTableAlias}.${id} in (select table_id from kaka_table_auth")
                .append(" where table_name = '")
                .append(authParamDTO.getTableName())
                .append("'");
        if (StringUtils.isEmpty(authParamDTO.getSpace())) {
            //主动授权权限
            stringBuilder.append(" and role_sec in (${roleList}) ");
        } else {
            //空间权限
            stringBuilder.append(" and space = ").append(authParamDTO.getSpace());
        }
        stringBuilder.append(")").append(" or auth.table_id is null)");

        //替换后sql
        StringBuilder sb = new StringBuilder()
                .append(StringPool.SINGLE_QUOTE)
                .append(StringUtils.join(authParamDTO.getRoleIdList(), StringPool.COMMA + StringPool.SINGLE_QUOTE + StringPool.COMMA))
                .append(StringPool.SINGLE_QUOTE);

        return stringBuilder.toString().replace("${id}", authParamDTO.getTableId())
                .replace("${mainTableAlias}", authParamDTO.getMainTableAlias())
                .replace("${roleList}", sb);
    }
}